package top.dtyy.concurrent.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author lzp
 * @version v1.0 at 2018/11/26
 */
public class MapExample {
    /**
     * 允许200个请求同时执行
     */
    private static int threadTotal = 2;
    /**
     * 模拟系统短时间内接收到5000个请求
     */
    private static int clientTotal = 5000;

    private static Map<Integer, Integer> map = new HashMap<>();

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        for (int index = 0; index < clientTotal; index++) {
            final int threadTotal = index;
            exec.execute(() -> {
                try {
                    semaphore.acquire();
                    func(threadTotal);
                    semaphore.release();
                } catch (Exception e) {
                    System.out.println("exception");
                }
            });
        }
        exec.shutdown();
        System.out.println(map.size());
    }

    private static void func(int threadTotal) {
        map.put(threadTotal, threadTotal);
    }
}
